package com.athuahua.function;

import org.junit.Test;

import java.util.UUID;
import java.util.function.*;

/**
 * @Author: huahua
 * @Date: 2024/10/24 0024
 * @Time: 16:22
 * @Description: accept 接受
 * apply 应用
 */
public class FunctionUse {
    @Test
    public void test01() {
        //有入参，无出参[消费者]
        //Bi 多个
        BiConsumer<String, String> consumer = (a, b) -> System.out.println("哈哈:" + a + "呵呵:" + b);
        consumer.accept("1", "2");

        //有入参，有出参[多功能函数]
        Function<String, Integer> function = x -> Integer.parseInt(x);
        System.out.println(function.apply("123"));


        //无入参，无出参[普通函数]
        Runnable runnable = () -> System.out.println("运行线程");
        new Thread(runnable).start();


        //无入参，有出参[提供者]
        Supplier<String> supplier = () -> UUID.randomUUID().toString().replaceAll("-", "");
        System.out.println(supplier.get());


        Predicate<Integer> even = (t) -> t % 2 == 0;
        System.out.println(even.test(6));
    }

    @Test
    public void demo() {
        //1.定义数据提供者函数
        Supplier<String> supplier = () -> "42";
        //2.断言，验证是否是个数字
        Predicate<String> isNumber = str -> str.matches("-?\\d+(\\.\\d+)?");
        //3.转化器：把字符串变成数字
        Function<String, Integer> toNumber = Integer::parseInt;
        //4.消费者，打印数字
        Consumer<Integer> consumer = integer -> {
            if (integer % 2 == 0) {
                System.out.println("是偶数" + integer);
            } else {
                System.out.println("是奇数" + integer);
            }
        };


        //串在一起
        //extracted(isNumber, supplier, consumer, toNumber);
        //最后会变成这么一个抽象玩意
        extracted(
                str -> str.matches("-?\\d+(\\.\\d+)?"),
                () -> "777",
                System.out::println,
                Integer::parseInt
        );
    }

    private static void extracted(
            Predicate<String> isNumber,
            Supplier<String> supplier,
            Consumer<Integer> consumer,
            Function<String, Integer> toNumber) {
        if (isNumber.test(supplier.get())) {
            consumer.accept(toNumber.apply(supplier.get()));
        } else {
            System.out.println("非法字符");
        }
    }
}















